package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
)

type CourseContentQueryParam struct {
	BaseQueryParam
}

type TypeAhead struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

type CourseContent struct {
	Id        int
	Title     string `orm:"column(title)"`
	SysUserId int    `orm:"column(sys_user_id)"`
	Content   string `orm:"column(content)" form:"Content"`
	CreateAt  int64  `orm:"column(create_at)"`
}

func (this *CourseContent) TableName() string {
	return CourseContentTBName()
}

func CourseContentTBName() string {
	return TableName("course_content")
}

func init() {
	orm.RegisterModel(new(CourseContent))
}

func CourseContentOne(id int) (*CourseContent, error) {
	o := orm.NewOrm()
	m := CourseContent{Id: id}
	err := o.Read(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}

func ContentDataList() ([]TypeAhead, error) {
	o := orm.NewOrm()
	var data []TypeAhead
	num, err := o.Raw("SELECT id, title as name from " + TableName("course_content")).QueryRows(&data)
	if err != nil {
		return nil, err
	}
	fmt.Println("content nums", num)
	return data, nil
}

func CourseContentPageList(params *CourseContentQueryParam) ([]*CourseContent, int64) {
	query := orm.NewOrm().QueryTable(CourseContentTBName())
	data := make([]*CourseContent, 0)

	sort := "Id"
	switch params.Sort {
	case "Id":
		sort = "Id"
	}

	if params.Order == "desc" {
		sort = "-" + sort
	}

	//if len(params.CourseName) > 0 {
	//	query = query.Filter("course_name__istartswith", params.CourseName)
	//}

	total, _ := query.Count()
	query.OrderBy(sort).Limit(params.Limit, params.Offset).All(&data)
	return data, total
}
